import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import _cache from '@/utils/cache'
import CONFIG from './config'

// create an axios instance
const service = axios.create({
  // baseURL: '/api',
  baseURL: CONFIG.baseURL,
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 30000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
	let token = _cache.get('token')
  console.log(token,'token');
    if (token) {
      if(config.params){
        config.params['token'] = token
      }
      if(config.data){
        config.data['token'] = token
      }
    }
    return config
  },
  error => {
    // do something with request error
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data

    // if the custom code is not 20000, it is judged as an error.
    return res
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service